<template>

	<view class="DetailView">
		<view class="content">
			<z-paging ref="paging" :refresher-only="true" :fixed="true" :show-loading-more-no-more-view='false'
				:refresher-enabled="false" :refresher-threshold="0" hide-refresher-when-reload
				hide-refresher-when-enabled>
				<template #top>
					<m-drag-button :style="{ opacity: BtnShow ? 1 : 0, }" :isDock="true" :existTabBar="true"
						:initialBottom="160" @btnClick="scan">
						<template #BtnContent>
							<u-icon name="scan" color="#fff" size="54rpx"></u-icon>
						</template>
					</m-drag-button>
					<u-navbar :fixed="false" title="模具保养" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff"
						@leftClick='leftClick'></u-navbar>
				</template>

				<view class="MainBox">
					<u--form labelPosition="left" :model="baseFormData" :rules="rules" ref="uForm">

						<u-form-item labelWidth="100" label="保养编号" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="order">
							<u--input v-model="baseFormData.BillNO" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="保养模具" borderBottom :leftIconStyle="{'font-size':'20px'}"
							prop="MoludName" required leftIcon="file-text" @click="openBaseScreen('模具','radio')">
							<u--input v-model="baseFormData.MoludName" placeholder="请选择模具名称" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item labelWidth="100" label="保养人员" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="calendar">
							<u--input v-model="baseFormData.UpkeepMan" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="开始时间" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="calendar">
							<u--input v-model="baseFormData.StartMaintenance" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="结束时间" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="calendar">
							<u--input v-model="baseFormData.EndMaintenance" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="保养周期" :leftIconStyle="{'font-size':'20px'}"
							prop="PeriodTypeName" required leftIcon="file-text" @click="openBaseScreen('周期','radio')">
							<u--input v-model="baseFormData.PeriodTypeName" placeholder="请选择周期" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</u--form>

					<view class="Main_CardListBox">
						<view class="CardBox" v-for="(item,index) in tableData" :key="index">
							<view class="Main_Card_Top">
								<view class="Main_Card_LeftBox x-f">
									<view class="OrdinalBox">
										<text>{{index + 1}}</text>
									</view>
									<view class="Title_Text x-f">
										<text>保养项目</text>
									</view>
								</view>
							</view>
							<view class="CommonBox">
								<u-cell title="保养项目">
									<template #value>
										<div class="CommonBoxDiv" :style="{ width: scrollLiftWidth + 'px'}">
											{{item.UpkeepItemName}}
										</div>
									</template>
								</u-cell>
								<u-cell title="保养结果" :border='false' class="custom-cell">
									<template slot="right-icon">
										<uni-data-checkbox v-model="item.FResult" :localdata="MaintenanceResultsList"
											:disabled="!submitButtonShow" />
									</template>
								</u-cell>
							</view>

						</view>
					</view>

				</view>
				<template #bottom>
					<view class="BottomBox" :style="$utils.disposeSafeBottomFun()" v-show="submitButtonShow">
						<button block @click="submit" style="width: 90%;margin: 0 auto !important;"
							class="content_bottom_primary_Btn">
							{{submitButton}}
						</button>
					</view>

				</template>
			</z-paging>

		</view>

		<u-modal :show="modalshow" :title="modaltitle" :content="modalcontent" :showCancelButton='true'
			@confirm='modalconfirm' @cancel='modalshow=false'>
		</u-modal>
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>

		<u-toast ref="uToast"></u-toast>

	</view>

</template>

<script>
	import {
		formatDateTime,
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime
	} from '@/st_mold/common/base.js';
	import BaseMixin from '@/st_mold/common/base.js';
	export default {
		mixins: [BaseMixin],
		data() {
			return {
				rules: {
					'MoludName': {
						type: 'string',
						required: true,
						message: '保养模具不能为空',
						trigger: ['change']
					},
					'PeriodTypeName': {
						type: 'string',
						required: true,
						message: '保养周期不能为空',
						trigger: ['change']
					}
				},


				modalshow: false, //模态框
				modaltitle: '提示', //模态框提示语
				modalcontent: '', //模态框提示语

				baseFormData: {
					PeriodTypeName: '周',
					PeriodType: 'W',
					UpkeepMan: '',
					BillDate: '',
					MoludName: '',
					MoludID: ''
				},

				MaintenanceResultsList: [], // 保养结果数组
				MaintenanceCycleList: [], // 保养周期
				tableData: [], // 子表

				value1: Number(new Date()), //时间值
				Timeshow: false, //时间是否显示
				submitButton: '', //按钮显示名称
				submitButtonShow: true, //按钮是否显示
				scrollLiftWidth: uni.getSystemInfoSync().windowWidth, //列表宽度
				MoludList: [],
				BtnShow: false,
			};
		},
		onLoad(item) {
			var that = this
			this.initData()
			// 判断是否有主表ID
			if (item.UpkeepMouldID) {
				// 获取详情
				that.queryList(item.UpkeepMouldID)
			} else {
				that.submitButton = '开始保养'
				// 保养人员
				this.baseFormData.UpkeepMan = this.baseFormData.UpkeepMan ? this.baseFormData.UpkeepMan : this
					.$store.state.UserInfo.UserName
				// 保养人员id
				this.baseFormData.CheckupID = this.baseFormData.CheckupID ? this.baseFormData.CheckupID : this.$store
					.state.UserInfo.EmplID
				// 保养日期
				this.baseFormData.BillDate = this.baseFormData.BillDate ? this.baseFormData.BillDate :
					getFormatDateTime(new Date())
				// 判断是否有模具id和保养周期id
				if (item.MoludID && item.PeriodType) {
					var obj = {
						FType: 'MJBY',
						MoludSelect: '',
						PageIndex: 1,
						PageSize: 30,
						IsInStorage: -1
					}
					that.Request.request('MJ_MoludList', obj, (ret) => {
						if (ret.status == 200) {
							that.MoludList = ret.data.ds
							var obj = ret.data.ds.find(ite => ite.MoludID == item.MoludID)
							that.baseFormData.MoludName = obj.MoludSelect
							that.baseFormData.MoludID = obj.MoludID
							that.baseFormData.PeriodType = item.PeriodType
							that.addPeriodTypeClick()
						}
					})

				}
			}
		},
		onUnload() {
			uni.$off('BatchEditScan');
			uni.$off('st_mold_Choice');
		},

		mounted() {
			var that = this;

			setTimeout(() => {
				that.BtnShow = true;
			}, 300)
			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})
			that.$nextTick(() => {
				that.scrollLiftWidth = (uni.getSystemInfoSync().windowWidth) / 3
			})
			uni.$on('st_mold_Choice', function(ret) {

				if (ret.type == '模具') {
					that.baseFormData.MoludID = ret.data.MoludID
					that.baseFormData.MoludName = ret.data.MoludSelect
					that.$refs.uForm.validateField('MoludName');
					that.AddgetCheckupItem()
				} else if (ret.type == '周期') {

					that.baseFormData.PeriodType = ret.data.ID
					that.baseFormData.PeriodTypeName = ret.data.NAME
					that.$refs.uForm.validateField('PeriodTypeName');
					if (that.baseFormData.MoludID) {
						that.AddgetCheckupItem()
					}
				}
			});

		},

		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onShow() {

		},
		methods: {
			// pda扫码
			scanHandler(scanData) {
				let that = this;
				if (that.submitButtonShow) {
					that.MoludChange(scanData.recode, 'pda')
				}

			},
			// 手机扫描
			scan() {
				let that = this;
				if (that.submitButtonShow) {
					that.$scanPopup.openScan({
						success: function(res) {

							that.MoludChange(res.result, 'phone')
						},
						fail: function(fail) {
							console.log(fail);
						}
					})
				}


			},
			// 处理扫码数据
			MoludChange(res, name) {
				let that = this;
				let parts = res.split("|");
				var id = parts[1]

				if (that.submitButtonShow) {
					var obj = {}
					if (parts[0] == 'MJ') {
						obj.MoludID = id

					} else if (parts[0] == 'MJKW') {
						obj.FStorageID = id
					}
					console.log(obj);
					that.Request.request('MJ_MoludList', obj, (ret) => {
						console.log(ret);
						if (ret.data.ds1[0].status == 500) {
							uni.$u.toast(ret.data.ds1[0].msg)
						} else {
							ret.data.ds.map(obj => {
								obj.WarningStatus = obj.WarningStatus ? obj.WarningStatus : 0
								obj.WarningStatusName = obj.WarningStatusName ? obj.WarningStatusName : ''
								obj.StockDeID = obj.StockDeID ? obj.StockDeID : 0
							})

							that.baseFormData.MoludID = ret.data.ds[0].MoludID
							that.baseFormData.MoludName = ret.data.ds[0].MoludSelect
							that.$refs.uForm.validateField('MoludName');
							that.AddgetCheckupItem()
						}
					})
				}

			},

			async initData() {
				// 加载公共字典数据
				await this.loadCommonDictionaries([{
						type: '保养周期',
						key: 'MaintenanceCycleList'
					},
					{
						type: '保养结果',
						key: 'MaintenanceResultsList'
					}
				]);
			},
			async addPeriodTypeClick() {
				var that = this
				// 直接使用缓存数据，避免重复请求
				if (!that.MaintenanceCycleList.length) {
					await that.initData();
				}
				const dictMappings = {
					PeriodType: {
						dictKey: 'MaintenanceCycle',
						targetField: 'PeriodTypeName'
					},
				};
				that.mapDictNamesForItem(that.baseFormData, dictMappings);
				that.AddgetCheckupItem();
			},
			// 模态框关闭
			modalconfirm() {
				var that = this
				that.modalshow = false
			},

			openBaseScreen(str, type) { // 前往筛选页
				let that = this;
				let obj = null;
				let url = '/commonPage/Tool/baseScreen';
				if (that.submitButton == '开始保养') {
					if (str == '模具') {
						obj = {
							allowClear: false,
							cmd: 'MJ_MoludList',
							type: str,
							ListeningName: 'st_mold_Choice',
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: 'MoludSelect', //搜索关键词，应包含在param中
								showText: 'MoludSelect', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								ChoiceDataKey: 'MoludID',
								ChoiceDataData: that.baseFormData.MoludID,
							},
							param: {
								FType: 'MJBY',
								MoludSelect: '',
								PageIndex: 1,
								PageSize: 30,
								IsInStorage: -1
							}
						}
					} else if (str == '周期') {
						obj = {
							allowClear: false,
							cmd: 'MJ_Dictionary',
							type: str,
							ListeningName: 'st_mold_Choice',
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'NAME', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								ChoiceDataKey: 'ID',
								ChoiceDataData: that.baseFormData.PeriodType,
							},
							param: {
								FType: '保养周期',
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					}
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})
					uni.navigateTo({
						url: url
					})
				}

			},

			// 时间赋值
			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				this.baseFormData.BillDate = time
				this.Timeshow = false
				this.$forceUpdate()
			},


			// 获取保养项目
			AddgetCheckupItem() {
				var that = this
				var obj = {
					MoludID: that.baseFormData.MoludID,
					PeriodType: that.baseFormData.PeriodType,
					FType: 'MJBY'
				}

				that.Request.request('getCheckupItem', obj, (ret) => {

					ret.data.ds.map(item => item.FResult = item.FResult ? item.FResult : 1)
					ret.data.ds.map(item => item.UpkeepMouldDeID = item.UpkeepMouldDeID ? item
						.UpkeepMouldDeID : 0)
					that.tableData = ret.data.ds
					that.$forceUpdate()
				})


			},
			// 新增
			submit() {
				var that = this
				this.$refs.uForm.validate().then(res => {

					var msg
					var show = true
					console.log(this.baseFormData);
					if (that.tableData.length == 0) {
						msg = '当前模具没有该保养周期'
						show = false
					}
					if (show) {
						var obj = {
							UpkeepMan: that.baseFormData.UpkeepMan,
							UpkeepMouldID: that.baseFormData.UpkeepMouldID ? that.baseFormData
								.UpkeepMouldID : 0,
							PeriodType: that.baseFormData.PeriodType,
							UpID: that.tableData.map(item => item.UpID).join(','),
							UpkeepItemID: that.tableData.map(item => item.UpkeepItemID).join(','),
							FResult: that.tableData.map(item => item.FResult).join(','),
							BillDate: that.baseFormData.BillDate,
							UpkeepItemContent: that.tableData.map(item => item.UpkeepItemContent).join(','),
							UpkeepMouldDeID: that.tableData.map(item => item.UpkeepMouldDeID).join(','),
							FType: 'MJBY',
							MoludID: that.baseFormData.MoludID
						}
						console.log(obj);
						that.Request.request('saveUpkeepMould', obj, function(ret) {
							console.log(ret);
							if (ret.status == 200) {
								if (ret.data.ds[0].status && ret.data.ds[0].status == 500) {
									uni.$u.toast(ret.data.ds[0].msg)
								} else {
									that.$refs.uToast.show({
										title: '保存',
										type: 'success',
										message: ret.data.ds[0].msg
									})
									that.queryList(ret.data.ds[0].UpkeepMouldID)
								}
							}
						})
					} else {

						that.modaltitle = '提醒'
						that.modalcontent = msg
						that.modalshow = true
					}

				}).catch(errors => {
					uni.$u.toast(errors[0].message)
				})

			},

			// 获取详情
			queryList(id) {
				var that = this
				try {
					that.Request.request('getUpkeepMouldDetail', {
						UpkeepMouldID: id
					}, (ret) => {
						console.log(ret);
						ret.data.ds.map((item) => {
							item.StartMaintenance = formatDateTime(item.StartMaintenance)
							item.EndMaintenance = formatDateTime(item.EndMaintenance)
							if (item.PeriodType) {

								const dictMappings = {
									PeriodType: {
										dictKey: 'MaintenanceCycle',
										targetField: 'PeriodTypeName'
									},
								};
								that.mapDictNamesForItem(item, dictMappings);
							}

						})
						that.baseFormData = ret.data.ds[0]

						that.tableData = ret.data.ds1

						that.$forceUpdate()
						if (that.baseFormData.BYStatus == 0) {
							that.submitButton = '开始保养'
						} else if (that.baseFormData.BYStatus == 1) {
							that.submitButton = '结束保养'
						} else {

							that.submitButtonShow = false
						}
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			// 关闭
			leftClick() {
				let routes = getCurrentPages(); //当前页面栈
				let prevPage = routes[routes.length - 2]
				prevPage.$vm.getList()
			}
		}
	}
</script>

<style lang="scss">
	@import "./css/index.scss";
</style>